package com.lcj.eduMsm.controller;

import com.lcj.commonutils.R;
import com.lcj.eduMsm.service.MsmService;
import com.lcj.eduMsm.utils.RandomUtil;
import net.bytebuddy.asm.Advice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author：LCJ
 * @Description：
 * @Date：Create in 10:00 2021/3/23 0023
 */
@RestController
@RequestMapping("/eduMsm/msm")
@CrossOrigin
public class MsmApiController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;


    //发送短信
    @GetMapping("send/{phone}")
    public R sendMsm(@PathVariable String phone){
        //从redis获取验证码
        String code = redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(code)){
            return R.ok();
        }

        //生成随机值传递给阿里云
        code = RandomUtil.getFourBitRandom();
        Map<String,Object> param =new HashMap<>();
        param.put("code",code);
        //调用service发送短信方法
        boolean isSend = msmService.send(param,phone);
        if(isSend){
            //发送成功，把发送成功验证按放入redis
            redisTemplate.opsForValue().set(phone,code,5,TimeUnit.MINUTES);
            return R.ok();
        }else{
            return R.error().message("短信发送失败");
        }
    }
}
